import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { inventoryCheckItems, inventoryCheck } from '@/lib/schema';
import { eq, and } from 'drizzle-orm';

export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json();
    const checkId = parseInt(params.id);
    
    const { itemId, actualQuantity, notes, checkedBy } = body;

    if (!itemId || actualQuantity === undefined) {
      return NextResponse.json(
        { error: '明细ID和实际数量不能为空' },
        { status: 400 }
      );
    }

    // 获取原明细信息
    const [existingItem] = await db
      .select()
      .from(inventoryCheckItems)
      .where(eq(inventoryCheckItems.id, itemId))
      .limit(1);

    if (!existingItem) {
      return NextResponse.json(
        { error: '盘点明细不存在' },
        { status: 404 }
      );
    }

    // 计算差异
    const discrepancy = actualQuantity - existingItem.systemQuantity;

    // 更新盘点明细
    const [updatedItem] = await db
      .update(inventoryCheckItems)
      .set({
        actualQuantity: actualQuantity,
        discrepancy: discrepancy,
        notes: notes || '',
        checkedBy: checkedBy || 'user',
        checkedAt: new Date(),
      })
      .where(eq(inventoryCheckItems.id, itemId))
      .returning();

    // 更新盘点单统计
    const checkItems = await db
      .select()
      .from(inventoryCheckItems)
      .where(eq(inventoryCheckItems.checkId, checkId));

    const checkedItems = checkItems.filter(item => item.checkedAt !== null).length;
    const discrepancies = checkItems.filter(item => item.discrepancy !== 0).length;

    await db
      .update(inventoryCheck)
      .set({
        checkedItems: checkedItems,
        discrepancies: discrepancies,
      })
      .where(eq(inventoryCheck.id, checkId));

    return NextResponse.json(updatedItem);

  } catch (error: any) {
    console.error('更新盘点明细失败:', error);
    return NextResponse.json(
      { error: '更新盘点明细失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}